package com.xysq.fragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.TextView;

import com.etsy.android.grid.StaggeredGridView;
import com.flyco.dialog.widget.NormalTipDialog;
import com.rockcent.action.CallbackListener;
import com.rockcent.model.BClientCustomerBO;
import com.rockcent.model.CustomerBO;
import com.rockcent.model.CustomerCouponBO;
import com.rockcent.model.constant.RealNameAuthType;
import com.xysq.activity.IdentifyActivity;
import com.xysq.activity.LoginActivity;
import com.xysq.activity.PublishGoodsActivity;
import com.xysq.adapter.WantBuyItemAdapter;
import com.xysq.lemon.R;
import com.xysq.util.ToastUtil;
import com.xysq.util.UserInfoKeeper;
import com.xysq.widget.LoadData;
import com.xysq.widget.ScrollListener;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link SkillFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SkillFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SkillFragment extends BaseFragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private SwipeRefreshLayout swipeRefreshLayout;
    private StaggeredGridView staggeredGridView;
    private WantBuyItemAdapter itemAdapter;
    TextView nullDataTxt;
    ScrollListener scrollListener;
    private View footerView;
    private ImageButton toPublishIbtn;

    TextView essenceTxt;
    TextView latestTxt;
    TextView insideSchoolTxt;
    TextView outsideSchoolTxt;
    int item;
    public static final int ESSENCE = 1;
    public static final int LATEST = 2;
    public static final int INSIDE_SCHOOL = 3;
    public static final int OUTSIDE_SCHOOL = 4;

    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SkillFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SkillFragment newInstance(String param1, String param2) {
        SkillFragment fragment = new SkillFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public SkillFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_skill, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ibtn_publish:
                toPublish();
                break;
            case R.id.txt_essence:
                item = ESSENCE;
                requestData();
                essenceTxt.setBackgroundColor(getResources().getColor(R.color.bg_blue));
                latestTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                insideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                outsideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                break;
            case R.id.txt_latest:
                item = LATEST;
                requestData();
                essenceTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                latestTxt.setBackgroundColor(getResources().getColor(R.color.bg_blue));
                insideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                outsideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                break;
            case R.id.txt_inside_school:
                item = INSIDE_SCHOOL;
                requestData();
                essenceTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                latestTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                insideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.bg_blue));
                outsideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                break;
            case R.id.txt_outside_school:
                item = OUTSIDE_SCHOOL;
                requestData();
                essenceTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                latestTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                insideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                outsideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.bg_blue));
                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        item = ESSENCE;
        essenceTxt = (TextView) getView().findViewById(R.id.txt_essence);
        latestTxt = (TextView) getView().findViewById(R.id.txt_latest);
        insideSchoolTxt = (TextView) getView().findViewById(R.id.txt_inside_school);
        outsideSchoolTxt = (TextView) getView().findViewById(R.id.txt_outside_school);
        essenceTxt.setBackgroundColor(getResources().getColor(R.color.bg_blue));
        essenceTxt.setOnClickListener(this);
        latestTxt.setOnClickListener(this);
        insideSchoolTxt.setOnClickListener(this);
        outsideSchoolTxt.setOnClickListener(this);
        footerView = LayoutInflater.from(getActivity()).inflate(R.layout.footer_load_more, null);
        staggeredGridView = (StaggeredGridView) getView().findViewById(R.id.staggered_grid_view);
        swipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.swipe);
        nullDataTxt = (TextView) getView().findViewById(R.id.txt_null_data);
        toPublishIbtn = (ImageButton) getView().findViewById(R.id.ibtn_publish);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                reloadData();
            }
        });
        toPublishIbtn.setOnClickListener(this);
        itemAdapter = new WantBuyItemAdapter(getActivity(), appAction);
        staggeredGridView.setAdapter(itemAdapter);
        staggeredGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                CustomerCouponBO couponBO = (CustomerCouponBO) itemAdapter.getItem(position);
//                Intent intent = new Intent(getActivity(), TipsActivity.class);
//                intent.putExtra(TipsActivity.COUPONMODEL_ID, couponBO.getId());
//                intent.putExtra(TipsActivity.CUSTOMER_ID, couponBO.getCustomerId());
//                startActivity(intent);
                clickSkill();

            }
        });
        scrollListener = new ScrollListener(staggeredGridView, true, new LoadData() {
            @Override
            public void loadMyData() {
                requestData();
            }
        });
        staggeredGridView.setOnScrollListener(scrollListener);
    }

    private void reloadData() {
        scrollListener.setCurrentPage(1);
        scrollListener.setLoadFinish(true);
        itemAdapter.clearItems();
        requestData();
    }

    private void clickSkill() {
        final NormalTipDialog dialog = new NormalTipDialog(getActivity());
        dialog.content("一大波技能正在路上")//
                .contentGravity(Gravity.CENTER)
                .isTitleShow(false)
                .btnText("确定")//
                .show();
    }

    /**
     * Called when the fragment is visible to the user and actively running.
     * This is generally
     * tied to {@link Activity#onResume() Activity.onResume} of the containing
     * Activity's lifecycle.
     */
    @Override
    public void onResume() {
        super.onResume();
        requestData();
    }

    private void requestData() {
        switch (item) {
            case ESSENCE:
                //TODO
                loadEssence();
                break;
            case LATEST:
                loadLatest();
                break;
            case INSIDE_SCHOOL:
                loadInsideSchool();
                break;
            case OUTSIDE_SCHOOL:
                loadOutsideSchool();
                break;
        }
    }

    private void loadInsideSchool() {
        appAction.getCustomer(UserInfoKeeper.readPhoneNumber(getActivity()), "", "", new CallbackListener<CustomerBO>() {
            @Override
            public void onSuccess(CustomerBO data) {
                appAction.listCustomerCouponsForPage(UserInfoKeeper.readCustomerId(getActivity()), data.getSchoolName(), scrollListener.getCurrentPage(), PAGE_SIZE, new CallbackListener<List<CustomerCouponBO>>() {
                    @Override
                    public void onSuccess(List<CustomerCouponBO> data) {
                        List<CustomerCouponBO> customerCouponBOs = new ArrayList<CustomerCouponBO>();
                        for (int i = 0; i < data.size(); i++) {
                            if (data.get(i).getIssueCount() != 0) {
                                customerCouponBOs.add(data.get(i));
                            }
                        }
                        if (scrollListener.getCurrentPage() == 1) {
                            if (customerCouponBOs.size() == 0) {
                                nullDataTxt.setVisibility(View.VISIBLE);
                            } else {
                                nullDataTxt.setVisibility(View.GONE);
                                itemAdapter.setItems(customerCouponBOs);
                            }
                        } else {
                            nullDataTxt.setVisibility(View.GONE);
                            if (customerCouponBOs.size() > 0) {
                                scrollListener.setLoadFinish(true);
                                itemAdapter.addItems(customerCouponBOs);
                            }
                        }
                        swipeRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onFailure(String errorCode, String message) {
                        scrollListener.setLoadFinish(true);
                        ToastUtil.showShort(getActivity(), message);
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onFailure(String errorCode, String message) {

            }
        });
    }

    private void loadOutsideSchool() {
        appAction.getCustomer(UserInfoKeeper.readPhoneNumber(getActivity()), "", "", new CallbackListener<CustomerBO>() {
            @Override
            public void onSuccess(CustomerBO data) {
                final String mySchool = data.getSchoolName();
                appAction.listCustomerCouponsForPage(UserInfoKeeper.readCustomerId(getActivity()), "", scrollListener.getCurrentPage(), PAGE_SIZE, new CallbackListener<List<CustomerCouponBO>>() {
                    @Override
                    public void onSuccess(List<CustomerCouponBO> data) {
                        List<CustomerCouponBO> customerCouponBOs = new ArrayList<CustomerCouponBO>();
                        for (int i = 0; i < data.size(); i++) {
                            if (!mySchool.equals(data.get(i).getExtend1())) {
                                if (data.get(i).getIssueCount() != 0) {
                                    customerCouponBOs.add(data.get(i));
                                }
                            }
                        }
                        if (scrollListener.getCurrentPage() == 1) {
                            if (customerCouponBOs.size() == 0) {
                                nullDataTxt.setVisibility(View.VISIBLE);
                            } else {
                                nullDataTxt.setVisibility(View.GONE);
                                itemAdapter.setItems(customerCouponBOs);
                            }
                        } else {
                            nullDataTxt.setVisibility(View.GONE);
                            if (customerCouponBOs.size() > 0) {
                                scrollListener.setLoadFinish(true);
                                itemAdapter.addItems(customerCouponBOs);
                            }
                        }
                        swipeRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onFailure(String errorCode, String message) {
                        scrollListener.setLoadFinish(true);
                        ToastUtil.showShort(getActivity(), message);
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onFailure(String errorCode, String message) {

            }
        });
    }

    private void loadLatest() {
        appAction.listCustomerCouponsForPage(UserInfoKeeper.readCustomerId(getActivity()), "", scrollListener.getCurrentPage(), PAGE_SIZE, new CallbackListener<List<CustomerCouponBO>>() {
            @Override
            public void onSuccess(List<CustomerCouponBO> data) {
                List<CustomerCouponBO> customerCouponBOs = new ArrayList<CustomerCouponBO>();
                for (int i = 0; i < data.size(); i++) {
                    if (data.get(i).getIssueCount() != 0) {
                        customerCouponBOs.add(data.get(i));
                    }
                }
                if (scrollListener.getCurrentPage() == 1) {
                    if (customerCouponBOs.size() == 0) {
                        nullDataTxt.setVisibility(View.VISIBLE);
                    } else {
                        nullDataTxt.setVisibility(View.GONE);
                        itemAdapter.setItems(customerCouponBOs);
                    }
                } else {
                    nullDataTxt.setVisibility(View.GONE);
                    if (customerCouponBOs.size() > 0) {
                        scrollListener.setLoadFinish(true);
                        itemAdapter.addItems(customerCouponBOs);
                    }
                }
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(String errorCode, String message) {
                scrollListener.setLoadFinish(true);
                ToastUtil.showShort(getActivity(), message);
                swipeRefreshLayout.setRefreshing(false);
            }
        });

    }

    private void loadEssence() {
        appAction.listCustomerCouponsForPage(UserInfoKeeper.readCustomerId(getActivity()), "", scrollListener.getCurrentPage(), PAGE_SIZE, new CallbackListener<List<CustomerCouponBO>>() {
            @Override
            public void onSuccess(List<CustomerCouponBO> data) {
                List<CustomerCouponBO> customerCouponBOs = new ArrayList<CustomerCouponBO>();
                for (int i = 0; i < data.size(); i++) {
                    if (data.get(i).getIssueCount() != 0) {
                        customerCouponBOs.add(data.get(i));
                    }
                }
                if (scrollListener.getCurrentPage() == 1) {
                    if (customerCouponBOs.size() == 0) {
                        nullDataTxt.setVisibility(View.VISIBLE);
                    } else {
                        nullDataTxt.setVisibility(View.GONE);
                        itemAdapter.setItems(customerCouponBOs);
                    }
                } else {
                    nullDataTxt.setVisibility(View.GONE);
                    if (customerCouponBOs.size() > 0) {
                        scrollListener.setLoadFinish(true);
                        itemAdapter.addItems(customerCouponBOs);
                    }
                }
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(String errorCode, String message) {
                scrollListener.setLoadFinish(true);
                ToastUtil.showShort(getActivity(), message);
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    //获取用户身份认证状态
    public void toPublish() {
        if (TextUtils.isEmpty(UserInfoKeeper.readPhoneNumber(getActivity()))) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
        } else {
            appAction.getBClientCustomer(UserInfoKeeper.readPhoneNumber(getActivity()), new CallbackListener<BClientCustomerBO>() {
                @Override
                public void onSuccess(BClientCustomerBO data) {
                    if (data != null) {
                        if (data.getIsRealnameAuth() == RealNameAuthType.UNAUTH) {//未实名认证，跳到实名认证页面
                            startActivity(new Intent(getActivity(), IdentifyActivity.class));
                        } else if (data.getIsRealnameAuth() == RealNameAuthType.FAIL) {
                            Intent intent = new Intent(getActivity(), IdentifyActivity.class);
                            intent.putExtra(IdentifyActivity.FAIL, IdentifyActivity.FAIL);
                            startActivity(intent);
                        } else if (data.getIsRealnameAuth() == RealNameAuthType.AUTHING) {
                            ToastUtil.showShort(getActivity(), getResources().getString(R.string.toast_authing));
                        } else if (data.getIsRealnameAuth() == RealNameAuthType.AUTH) {
                            Intent intent = new Intent(getActivity(), PublishGoodsActivity.class);
                            startActivity(intent);
                        }
                    } else {
                        ToastUtil.showShort(getActivity(), "获取认证信息失败");
                    }
                }

                @Override
                public void onFailure(String errorCode, String message) {

                }
            });
        }
    }
}
